<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/my_blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/my_blog/css/main.css?v=6.3.0" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/my_blog/images/apple-touch-icon-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/my_blog/images/favicon-32x32-next.png?v=6.3.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/my_blog/images/favicon-16x16-next.png?v=6.3.0">


  <link rel="mask-icon" href="/my_blog/images/logo.svg?v=6.3.0" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/my_blog/',
    scheme: 'Pisces',
    version: '6.3.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content=".NET 中的异步/多线程/并发处理(2) - 异步本文核心：  如何使用户交互界面具有良好的响应？ 如何最大化利用CPU的性能？  针对上面两个问题，根据 .NET Guide 中的 Parallel Processing, Concurrency, and Async Programming in .NET 的内容，进一步深入理解 .NET 的下面三种机制：  异步编程 并行处理 多线程与线程">
<meta name="keywords" content="CSharp">
<meta property="og:type" content="article">
<meta property="og:title" content="Parallel Processing, Concurrency, and Async Programming in .NET - 2">
<meta property="og:url" content="http://sdfsd23few23.gitee.io/my_blog/2018/06/20/DotNet-Guide-Async-Programming/index.html">
<meta property="og:site_name" content="Raymond&#39;s Blog">
<meta property="og:description" content=".NET 中的异步/多线程/并发处理(2) - 异步本文核心：  如何使用户交互界面具有良好的响应？ 如何最大化利用CPU的性能？  针对上面两个问题，根据 .NET Guide 中的 Parallel Processing, Concurrency, and Async Programming in .NET 的内容，进一步深入理解 .NET 的下面三种机制：  异步编程 并行处理 多线程与线程">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://sdfsd23few23.gitee.io/my_blog/2018/06/20/DotNet-Guide-Async-Programming/async_workflow.png">
<meta property="og:updated_time" content="2018-06-24T11:19:59.426Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Parallel Processing, Concurrency, and Async Programming in .NET - 2">
<meta name="twitter:description" content=".NET 中的异步/多线程/并发处理(2) - 异步本文核心：  如何使用户交互界面具有良好的响应？ 如何最大化利用CPU的性能？  针对上面两个问题，根据 .NET Guide 中的 Parallel Processing, Concurrency, and Async Programming in .NET 的内容，进一步深入理解 .NET 的下面三种机制：  异步编程 并行处理 多线程与线程">
<meta name="twitter:image" content="http://sdfsd23few23.gitee.io/my_blog/2018/06/20/DotNet-Guide-Async-Programming/async_workflow.png">






  <link rel="canonical" href="http://sdfsd23few23.gitee.io/my_blog/2018/06/20/DotNet-Guide-Async-Programming/"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>Parallel Processing, Concurrency, and Async Programming in .NET - 2 | Raymond's Blog</title>
  









  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/my_blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Raymond's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">CSharp & Java</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="Toggle navigation bar">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">
    <a href="/my_blog/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-home"></i> <br />Startseite</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">
    <a href="/my_blog/tags/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />Tags</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">
    <a href="/my_blog/categories/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-th"></i> <br />Kategorien</a>
  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">
    <a href="/my_blog/archives/" rel="section">
      <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />Archiv</a>
  </li>

      
      
    </ul>
  

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://sdfsd23few23.gitee.io/my_blog/my_blog/2018/06/20/DotNet-Guide-Async-Programming/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Raymond">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/my_blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Raymond's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Parallel Processing, Concurrency, and Async Programming in .NET - 2
              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Veröffentlicht am</span>
              

              
                
              

              <time title="Post created: 2018-06-20 18:56:58" itemprop="dateCreated datePublished" datetime="2018-06-20T18:56:58+08:00">2018-06-20</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">Edited on</span>
                
                <time title="Updated at: 2018-06-24 19:19:59" itemprop="dateModified" datetime="2018-06-24T19:19:59+08:00">2018-06-24</time>
              
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">in</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing"><a href="/my_blog/categories/Coding/" itemprop="url" rel="index"><span itemprop="name">Coding</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="NET-中的异步-多线程-并发处理-2-异步"><a href="#NET-中的异步-多线程-并发处理-2-异步" class="headerlink" title=".NET 中的异步/多线程/并发处理(2) - 异步"></a>.NET 中的异步/多线程/并发处理(2) - 异步</h1><p>本文核心：</p>
<ol>
<li>如何使用户交互界面具有良好的响应？</li>
<li>如何最大化利用CPU的性能？</li>
</ol>
<p>针对上面两个问题，根据 .NET Guide 中的 <a href="https://docs.microsoft.com/en-us/dotnet/standard/parallel-processing-and-concurrency" target="_blank" rel="noopener">Parallel Processing, Concurrency, and Async Programming in .NET</a> 的内容，进一步深入理解 .NET 的下面三种机制：</p>
<ol>
<li>异步编程</li>
<li>并行处理</li>
<li>多线程与线程同步机制。</li>
</ol>
<h2 id="异步编程"><a href="#异步编程" class="headerlink" title="异步编程"></a>异步编程</h2><p>异步编程的核心在于将所有阻塞主线程（UI线程）的操作，放到后台线程中执行，使程序具有良好的响应。</p>
<p>.NET 中的异步编程具有三种模式（pattern）：</p>
<ol>
<li>Asynchronous Programming Model (APM) pattern (also called the IAsyncResult pattern)</li>
<li>Event-based Asynchronous Pattern (EAP)</li>
<li>Task-based Asynchronous Pattern (TAP)</li>
</ol>
<h3 id="1-APM模式"><a href="#1-APM模式" class="headerlink" title="1. APM模式"></a>1. APM模式</h3><p>此模式使用 <a href="https://docs.microsoft.com/en-us/dotnet/api/system.iasyncresult" target="_blank" rel="noopener">IAsyncResult</a> 接口，并通过成对的 Begin<em>OperationName</em> 和 End<em>OperationName</em> 方法开始/终止异步操作。</p>
<pre><code>例：FileStream 提供 BeginRead 和 EndRead 方法来读取文件内容
</code></pre><p>在调用 Begin<em>OperationName</em> 方法后，调用线程会继续向下执行，而异步操作会在另一个线程中执行。每次调用 Begin<em>OperationName</em> 后，都应调用 End<em>OperationName</em> 来获取异步操作的结果。</p>
<p>需要注意：当调用 End<em>OperationName</em> 时异步操作还没有完成，那么调用线程会等待，直到异步操作完成。异步操作中出现的异常会从 End<em>OperationName</em> 方法中抛出。</p>
<p>采用阻塞的方式的两个例子：</p>
<ol>
<li><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/blocking-application-execution-by-ending-an-async-operation" target="_blank" rel="noopener">Blocking Application Execution by Ending an Async Operation</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/blocking-application-execution-using-an-asyncwaithandle" target="_blank" rel="noopener">Blocking Application Execution Using an AsyncWaitHandle</a></li>
</ol>
<p>采用非阻塞有两种方式，一种是监控IsComplete属性，一种是使用使用AysncCallback函数的方式：</p>
<ol>
<li><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/polling-for-the-status-of-an-asynchronous-operation" target="_blank" rel="noopener">Polling for the Status of an Asynchronous Operation</a></li>
<li><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/using-an-asynccallback-delegate-to-end-an-asynchronous-operation" target="_blank" rel="noopener">Using an AsyncCallback Delegate to End an Asynchronous Operation</a></li>
</ol>
<h3 id="2-基于事件的异步"><a href="#2-基于事件的异步" class="headerlink" title="2. 基于事件的异步"></a>2. 基于事件的异步</h3><p>如果你的程序需要同时处理多个任务，那么System.Threading命名空间中能满足大部分复杂的需求,但是如果你的需求比较简单，那么可以考虑使用基于事件的异步，一个直接的例子是 <a href="https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker" target="_blank" rel="noopener">BackgroundWorker</a>，它能完成一个后台任务，但是如果你需要同时运行多个独立的任务，那么可以考虑实现一个符合基于事件异步设计模式。</p>
<p>基于事件的异步操作设计模式，一般包含一对或多对 <em>MethodName</em>Async 方法和 <em>MethodName</em>Completed 事件。如果想要支持取消异步操作的功能，则可以拥有一个或多个<em>MethodName</em>CancelAsync 方法。而具体实现方式通过多线程，这部分在后边会提到。</p>
<h3 id="3-基于任务的异步"><a href="#3-基于任务的异步" class="headerlink" title="3. 基于任务的异步"></a>3. 基于任务的异步</h3><p>基于任务的异步的核心是 System.Threading.Tasks.Task 和 System.Threading.Tasks.Task<tresult> 类型。</tresult></p>
<ul>
<li><strong>Task</strong> 表示一个没有返回类型的任务</li>
<li><strong>Task\<t></t></strong> 表示一个具有返回类型为T的任务</li>
</ul>
<p>基于任务的异步是微软推荐的异步编程模型。</p>
<p>微软还提供了 async 和 await 关键字（C# 5.0 &amp; .NET Framework 4.5) 来大幅度简化异步编程，它们与 Task 一起使用，就能编写出简单、直观、易读、稳定性高的异步操作代码。</p>
<h4 id="async-await-关键字"><a href="#async-await-关键字" class="headerlink" title="async/await 关键字"></a>async/await 关键字</h4><p>使用 async 和 await 关键字可以让你用编写同步操作一样的方式，编写异步操作。一个异步方法使用 async 关键字修饰，方法体内部会有使用 await 关键字修饰的方法，下面我们通过一个例子说明如何使用这两个关键字以及使用这种编程方式的优势。</p>
<pre><code>// Mark the event handler with async so you can use await in it.
private async void StartButton_Click(object sender, RoutedEventArgs e)
{
    // Call and await separately.
    //Task&lt;int&gt; getLengthTask = AccessTheWebAsync();
    //// You can do independent work here.
    //int contentLength = await getLengthTask;

    int contentLength = await AccessTheWebAsync();

    resultsTextBox.Text +=
        String.Format(&quot;\r\nLength of the downloaded string: {0}.\r\n&quot;, contentLength);

}

// Three things to note in the signature:
//  - The method has an async modifier. 
//  - The return type is Task or Task&lt;T&gt;. (See &quot;Return Types&quot; section.)
//    Here, it is Task&lt;int&gt; because the return statement returns an integer.
//  - The method name ends in &quot;Async.&quot;
async Task&lt;int&gt; AccessTheWebAsync()
{ 
    // You need to add a reference to System.Net.Http to declare client.
    HttpClient client = new HttpClient();

    // GetStringAsync returns a Task&lt;string&gt;. That means that when you await the
    // task you&apos;ll get a string (urlContents).
    Task&lt;string&gt; getStringTask = client.GetStringAsync(&quot;http://msdn.microsoft.com&quot;);

    // You can do work here that doesn&apos;t rely on the string from GetStringAsync.
    DoIndependentWork();

    // The await operator suspends AccessTheWebAsync.
    //  - AccessTheWebAsync can&apos;t continue until getStringTask is complete.
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync.
    //  - Control resumes here when getStringTask is complete. 
    //  - The await operator then retrieves the string result from getStringTask.
    string urlContents = await getStringTask;

    // The return statement specifies an integer result.
    // Any methods that are awaiting AccessTheWebAsync retrieve the length value.
    return urlContents.Length;
}

void DoIndependentWork()
{
    resultsTextBox.Text += &quot;Working . . . . . . .\r\n&quot;;
}
</code></pre><p>上面的例子主要完成：点击按钮后，加载一个网页，在网页加载完成后将网页的字节数显示在 TextBox 中。</p>
<p>可以看到如果把 async 和 await 关键字去掉，这就是一个同步处理的过程，调用一个方法加载网页，加载后获取字节数，然后显示。</p>
<p>根据上面的代码我们总结一下一个 async 方法的特点：</p>
<ol>
<li>使用 async 关键字修饰方法声明</li>
<li>方法名称使用“Async”后缀</li>
<li>返回类型为：Task/Task\<t></t></li>
<li>方法体内至少有一个 await 语句，说明本方法应等待哪个异步方法完成。</li>
</ol>
<h4 id="async-方法的执行时序"><a href="#async-方法的执行时序" class="headerlink" title="async 方法的执行时序"></a>async 方法的执行时序</h4><p><img src="/my_blog/2018/06/20/DotNet-Guide-Async-Programming/async_workflow.png" alt="执行时序" title="async 方法的执行时序"></p>
<h4 id="async-方法中的线程"><a href="#async-方法中的线程" class="headerlink" title="async 方法中的线程"></a>async 方法中的线程</h4><p>当程序执行到 async 方法中的 await 语句修饰的方法时，而调用线程会立刻返回，而剩余的语句会在被 await 修饰的方法完成后，再执行。需要注意的是，上述过程并不会创建额外的线程（在我阅读到这部分时十分困惑），异步方法不要求多线程，因为异步方法不会创建一个线程并运行在创建的线程上，而是运行在UI线程（SynchronizationContext）。对于CPU-bound（后续详解）任务来说，建立一个其他线程不会对减少运行时间有所帮助。</p>
<p>但是对于ConsoleApp来说情况有点不一样，因为只有窗体程序（Winform,WPF..)才会有 SynchronizationContext 这个对象，对于ConsoleApp来说异步方法是会运行在一个其他线程上的。在我刚阅读到这段的时候，我还专门做了个实验，发现居然和文章中说的不一样，我还以为我理解错了，后来在 Stackoverflow 的找到有个人和我有一样的问题 <a href="https://stackoverflow.com/questions/40249169/async-await-and-threading" target="_blank" rel="noopener">async await and threading</a>。这里我贴一下正确的回答:</p>
<p><code>the way that async/await works in a console application is very different than how it works in a UI application due to the lack of a synchronization context in a console application.</code><br><a href="https://blogs.msdn.microsoft.com/pfxteam/2012/01/20/await-synchronizationcontext-and-console-apps/" target="_blank" rel="noopener">This article</a><br><code>describes details and gives a code sample of how add one so that async/await behaves in a more predictable way.</code></p>
<h4 id="I-O-bound-和-CPU-bound"><a href="#I-O-bound-和-CPU-bound" class="headerlink" title="I/O-bound 和 CPU-bound"></a>I/O-bound 和 CPU-bound</h4><p>计算机的两种典型操作：I/O-bound 和 CPU-bound。</p>
<p>I/O-bound (I/O密集型)：涉及到网络、磁盘IO的任务都是IO密集型任务，这类任务的特点是CPU消耗很少，任务的大部分时间都在等待IO操作完成（因为IO的速度远远低于CPU和内存的速度）。对于IO密集型任务，任务越多，CPU效率越高，但也有一个限度。</p>
<p>CPU-bound (计算密集型)操作：计算密集型任务的特点是要进行大量的计算，消耗CPU资源，比如计算圆周率、对视频进行高清解码等等，全靠CPU的运算能力。这种计算密集型任务虽然也可以用多任务完成，但是任务越多，花在任务切换的时间就越多，CPU执行任务的效率就越低，所以，要最高效地利用CPU，计算密集型任务同时进行的数量应当等于CPU的核心数。</p>
<p>下面的代码是 I/O-bound 和 CPU-bound 两种情况下的基于任务的异步模式的例子，通过代码说明基于任务的异步模式的优点和特性。</p>
<h4 id="I-O-bound-Task"><a href="#I-O-bound-Task" class="headerlink" title="I/O-bound Task"></a>I/O-bound Task</h4><p>下面的代码是一个典型的异步I/O操作，GetHtmlAsync 方法返回一个可以运行的Task。</p>
<pre><code>public Task&lt;string&gt; GetHtmlAsync()
{
    // Execution is synchronous here
    var client = new HttpClient();

    return client.GetStringAsync(&quot;http://www.dotnetfoundation.org&quot;);
}
</code></pre><p>第二个例子使用 async 和 await 操作Task。</p>
<pre><code>public async Task&lt;string&gt; GetFirstCharactersCountAsync(string url, int count)
{
    // Execution is synchronous here
    var client = new HttpClient();

    // Execution of GetFirstCharactersCountAsync() is yielded to the caller here
    // GetStringAsync returns a Task&lt;string&gt;, which is *awaited*
    var page = await client.GetStringAsync(&quot;http://www.dotnetfoundation.org&quot;);

    // Execution resumes when the client.GetStringAsync task completes,
    // becoming synchronous again.

    if (count &gt; page.Length)
    {
        return page;
    }
    else
    {
        return page.Substring(0, count);
    }
}
</code></pre><p>通过上面这两种基于任务（Task）的异步模式处理I/O操作，操作系统就能利用 Interrupt Request Packet (IRP)的方式，使宝贵的CPU时间，不浪费在等待缓慢的I/O操作完成上。</p>
<p>虽然看上去有另一个线程在处理I/O操作，但其实没有任何线程专门运行这个Task，也就是说没有一个线程是在等待I/O操作完成。一个I/O操作的Task的执行过程是：某个线程调用操作系统底层I/O驱动，向驱动发送操作指令，然后直接返回（此时本线程退出），驱动最终完成I/O操作完成后通过 IRP 通知操作系统，然后操作系统在把数据交给一个可用线程进行处理，最终把结果返回给调用者。</p>
<p>上述的过程，最终效果就是CPU能处理大量的I/O操作，而不是把时间浪费在等待I/O操作结束上。</p>
<p>对服务端来说，比如一个网页服务器，它的意义在于能更高效的利用CPU，处理更多的客户端请求。</p>
<p>对于客户端来说，虽然你也可以通过手动增加后台线程的方式实现异步操作，使你的程序具有良好的界面响应，但是相比于使用 await 和 async 的 Task 方式的异步模式，效率更低也更加复杂。还有一方面是因为I/O操作基本不占用CPU，如果你把一个线程专门用来等待I/O操作是一种资源的浪费。</p>
<h4 id="CPU-bound-Task"><a href="#CPU-bound-Task" class="headerlink" title="CPU-bound Task"></a>CPU-bound Task</h4><p>CPU-bound的异步代码和I/O-bound的代码不同，因为任务需要CPU来执行，所以必定需要指定一个线程来进行计算，所以对于此类任务，async 和 await 的作用只是给你提供一个简单清晰的方法去操作后台线程。</p>
<p>下面是一个CPU-bound 异步调用：</p>
<pre><code>public async Task&lt;int&gt; CalculateResult(InputData data)
{
    // This queues up the work on the threadpool.
    var expensiveResultTask = Task.Run(() =&gt; DoExpensiveCalculation(data));

    // Note that at this point, you can do some other work concurrently,
    // as CalculateResult() is still executing!

    // Execution of CalculateResult is yielded here!
    var result = await expensiveResultTask;

    return Math.Abs(result);
}
</code></pre><p>可以看到，代码使用了 Task.Run 将 DoExpensiveCalculation 的计算加入 ThreadPool 中去运行（可能会是在另一个CPU核心上）。</p>
<h4 id="监控进度"><a href="#监控进度" class="headerlink" title="监控进度"></a>监控进度</h4><p>监控进度的例子：</p>
<pre><code>private async void btnDownload_Click(object sender, RoutedEventArgs e)    
{  
    btnDownload.IsEnabled = false;  
    try  
    {  
        txtResult.Text = await DownloadStringAsync(txtUrl.Text,   
            new Progress&lt;int&gt;(p =&gt; pbDownloadProgress.Value = p));  
    }  
    finally { btnDownload.IsEnabled = true; }  
}
</code></pre><h4 id="进阶-async-方法中的并行处理"><a href="#进阶-async-方法中的并行处理" class="headerlink" title="进阶 - async 方法中的并行处理"></a>进阶 - async 方法中的并行处理</h4><p><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern#taskfromresult" target="_blank" rel="noopener">Task.FromResult</a></p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/how-to-extend-the-async-walkthrough-by-using-task-whenall" target="_blank" rel="noopener">Task.WhenAll</a></p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern#redundancy" target="_blank" rel="noopener">Redundancy</a></p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern#taskwhenany" target="_blank" rel="noopener">Task.WhenAny</a></p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern#interleaving" target="_blank" rel="noopener">Interleaving</a></p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern#throttling" target="_blank" rel="noopener">Throttling</a></p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern#taskdelay" target="_blank" rel="noopener">Task.Delay</a></p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/standard/asynchronous-programming-patterns/consuming-the-task-based-asynchronous-pattern#early-bailout" target="_blank" rel="noopener">Early Bailout</a></p>
<p><a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/how-to-make-multiple-web-requests-in-parallel-by-using-async-and-await" target="_blank" rel="noopener">Parallel by Using async and await</a></p>

      
    </div>

    

    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/my_blog/tags/CSharp/" rel="tag"># CSharp</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/my_blog/2018/04/09/CSharp-to-Java-2/" rel="next" title="CSharp to Java #2">
                <i class="fa fa-chevron-left"></i> CSharp to Java #2
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/my_blog/2018/06/24/DotNet-Guide-Parallel-Programming/" rel="prev" title="Parallel Processing, Concurrency, and Async Programming in .NET - 3">
                Parallel Processing, Concurrency, and Async Programming in .NET - 3 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            Inhaltsverzeichnis
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            Übersicht
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">Raymond</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/my_blog/archives/">
                
                    <span class="site-state-item-count">12</span>
                    <span class="site-state-item-name">Artikel</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/my_blog/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">Kategorien</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/my_blog/Tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">11</span>
                    <span class="site-state-item-name">Tags</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#NET-中的异步-多线程-并发处理-2-异步"><span class="nav-number">1.</span> <span class="nav-text">.NET 中的异步/多线程/并发处理(2) - 异步</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#异步编程"><span class="nav-number">1.1.</span> <span class="nav-text">异步编程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-APM模式"><span class="nav-number">1.1.1.</span> <span class="nav-text">1. APM模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-基于事件的异步"><span class="nav-number">1.1.2.</span> <span class="nav-text">2. 基于事件的异步</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-基于任务的异步"><span class="nav-number">1.1.3.</span> <span class="nav-text">3. 基于任务的异步</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#async-await-关键字"><span class="nav-number">1.1.3.1.</span> <span class="nav-text">async/await 关键字</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#async-方法的执行时序"><span class="nav-number">1.1.3.2.</span> <span class="nav-text">async 方法的执行时序</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#async-方法中的线程"><span class="nav-number">1.1.3.3.</span> <span class="nav-text">async 方法中的线程</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#I-O-bound-和-CPU-bound"><span class="nav-number">1.1.3.4.</span> <span class="nav-text">I/O-bound 和 CPU-bound</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#I-O-bound-Task"><span class="nav-number">1.1.3.5.</span> <span class="nav-text">I/O-bound Task</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#CPU-bound-Task"><span class="nav-number">1.1.3.6.</span> <span class="nav-text">CPU-bound Task</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#监控进度"><span class="nav-number">1.1.3.7.</span> <span class="nav-text">监控进度</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#进阶-async-方法中的并行处理"><span class="nav-number">1.1.3.8.</span> <span class="nav-text">进阶 - async 方法中的并行处理</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Raymond</span>

  

  
</div>




  <div class="powered-by">Erstellt mit  <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> v3.7.1</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://theme-next.org">NexT.Pisces</a> v6.3.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/my_blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/my_blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/my_blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/my_blog/js/src/utils.js?v=6.3.0"></script>

  <script type="text/javascript" src="/my_blog/js/src/motion.js?v=6.3.0"></script>



  
  


  <script type="text/javascript" src="/my_blog/js/src/affix.js?v=6.3.0"></script>

  <script type="text/javascript" src="/my_blog/js/src/schemes/pisces.js?v=6.3.0"></script>



  
  <script type="text/javascript" src="/my_blog/js/src/scrollspy.js?v=6.3.0"></script>
<script type="text/javascript" src="/my_blog/js/src/post-details.js?v=6.3.0"></script>



  


  <script type="text/javascript" src="/my_blog/js/src/bootstrap.js?v=6.3.0"></script>



  



	





  





  










  





  

  

  

  

  
  

  

  

  

  

  

</body>
</html>
